package com.wwj.core.wawa.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wwj.core.wawa.entity.PlayRecord;
import com.wwj.core.wawa.entity.UploadFile;
import com.wwj.core.wawa.entity.mapper.PlayRecordMapper;
import com.wwj.core.wawa.entity.mapper.UploadFileMapper;
import com.wwj.core.wawa.service.IUploadFileService;
import com.wwj.utils.OSSClientUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UploadFileServiceImpl implements IUploadFileService {

    @Resource
    private UploadFileMapper uploadFileMapper;

    @Resource
    private PlayRecordMapper playRecordMapper;

    @Override
    public Page<UploadFile> findByPlayerId(int playerId, int offset, int limit) {
        PageHelper.offsetPage(offset, limit);
        return (Page<UploadFile>)uploadFileMapper.selectUploadFilesByPlayerId(playerId);
    }

    @Override
    public void dealUploadFile(int playerId, List<Map<String, Object>> files) throws Exception {
        for(Map<String, Object> fileInfo : files) {
            String url = uploadToOOS(playerId, fileInfo);
            System.out.println("上传文件URL：" + OSSClientUtil.URL_PREFIX + url);
            UploadFile file = new UploadFile();
            file.setPlayerId(playerId);
            file.setName((String)fileInfo.get("name"));
            file.setSize((Long) fileInfo.get("size"));
            file.setUrl(OSSClientUtil.URL_PREFIX + url);
            file.setUploadTime(new Date());
            uploadFileMapper.insertUploadFile(file);

            //将游戏录屏文件与游戏记录对应起来
            PlayRecord playRecord = playRecordMapper.selectPlayRecordByToken((String)fileInfo.get("name"));
            if(playRecord != null) {
                playRecord.setVideoStatus(PlayRecord.VIDEO_AVAILABLE);
                playRecord.setVideoUrl(OSSClientUtil.URL_PREFIX + url);
                playRecordMapper.updatePlayRecord(playRecord);
            }
        }
    }

    private String uploadToOOS(int playerId, Map<String, Object> fileInfo) throws Exception {
        File originalFile = (File) fileInfo.get("file");
        String folderPath = "wwj/files/" + playerId + "/video/";
        String fileName = (String)fileInfo.get("name");
        int index = fileName.lastIndexOf(".");
        if(index >= 0) {
            fileName = fileName.substring(index);
        }
        fileName = System.currentTimeMillis() + fileName;
        OSSClientUtil.putFile(folderPath, fileName, new FileInputStream(originalFile), "video/mp4", (Long)fileInfo.get("size"));
        return folderPath + fileName;
    }
}
